package com.monitoring.domain.service;

import com.monitoring.domain.entity.Sensor;
import com.monitoring.domain.repository.SensorRepository;
import com.monitoring.domain.valueobject.Temperature;
import com.monitoring.domain.valueobject.Humidity;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class SensorService {
    private final SensorRepository sensorRepository;
    
    public SensorService(SensorRepository sensorRepository) {
        this.sensorRepository = sensorRepository;
    }
    
    // 创建传感器
    public Sensor createSensor(String name, String location, String type) {
        if (name == null || name.isEmpty()) {
            throw new IllegalArgumentException("传感器名称不能为空");
        }
        
        Sensor sensor = new Sensor();
        sensor.setName(name);
        sensor.setLocation(location);
        sensor.setType(type);
        sensor.setActive(true);
        
        return sensorRepository.save(sensor);
    }
    
    // 根据ID查找传感器
    public Optional<Sensor> getSensorById(Long id) {
        return sensorRepository.findById(id);
    }
    
    // 获取所有传感器
    public List<Sensor> getAllSensors() {
        return sensorRepository.findAll();
    }
    
    // 根据位置查找传感器
    public List<Sensor> getSensorsByLocation(String location) {
        return sensorRepository.findByLocation(location);
    }
    
    // 获取活跃的传感器
    public List<Sensor> getActiveSensors() {
        return sensorRepository.findActiveSensors();
    }
    
    // 更新传感器读数（示例方法，实际可能在EnvironmentalDataService中实现）
    public void updateSensorReading(Long sensorId, double temperature, double humidity) {
        // 这里可以添加数据验证逻辑
        Temperature temp = new Temperature(temperature, "Celsius");
        Humidity hum = new Humidity(humidity);
        
        // 可以添加异常温度或湿度的处理逻辑
        if (temp.isHigh()) {
            // 触发高温警报逻辑
        }
    }
    
    // 激活传感器
    public Sensor activateSensor(Long id) {
        Optional<Sensor> optionalSensor = sensorRepository.findById(id);
        if (optionalSensor.isPresent()) {
            Sensor sensor = optionalSensor.get();
            sensor.activate();
            return sensorRepository.save(sensor);
        }
        throw new IllegalArgumentException("传感器不存在");
    }
    
    // 停用传感器
    public Sensor deactivateSensor(Long id) {
        Optional<Sensor> optionalSensor = sensorRepository.findById(id);
        if (optionalSensor.isPresent()) {
            Sensor sensor = optionalSensor.get();
            sensor.deactivate();
            return sensorRepository.save(sensor);
        }
        throw new IllegalArgumentException("传感器不存在");
    }
    
    // 删除传感器
    public void deleteSensor(Long id) {
        if (sensorRepository.existsById(id)) {
            sensorRepository.deleteById(id);
        } else {
            throw new IllegalArgumentException("传感器不存在");
        }
    }
}